//
// Created by rebeater on 2020/8/28.
//

#include "rtklib_custom.h"

static int nepoch = 0;            /* number of observation epochs */
static int iobsu = 0;            /* current rover observation data index */
static int iobsr = 0;            /* current reference observation data index */
static int isbs = 0;            /* current sbas message index */
static int ilex = 0;            /* current lex message index */
static int revs = 0;            /* analysis direction (0:forward,1:backward) */


/* show message --------------------------------------------------------------*/
extern int showmsg(char *format, ...) {
    va_list arg;
    va_start(arg, format);
    vfprintf(stderr, format, arg);
    va_end(arg);
    fprintf(stderr, "\r");
    return 0;
}
extern void settspan(gtime_t ts, gtime_t te) {}
extern void settime(gtime_t time) {}


/* search next observation data index ----------------------------------------*/
static int nextobsf(const obs_t *obs, int *i, int rcv) {
    double tt;
    int n;

    for (; *i < obs->n; (*i)++) if (obs->data[*i].rcv == rcv) break;
    for (n = 0; *i + n < obs->n; n++) {
        tt = timediff(obs->data[*i + n].time, obs->data[*i].time);
        if (obs->data[*i + n].rcv != rcv || tt > DTTOL) break;
    }
    return n;
}

/* input obs data, navigation messages and sbas correction -------------------*/
int inputobs(obsd_t *obs, int solq, const prcopt_t *popt, obs_t *obss) {
    gtime_t time = {0};
    char path[1024];
    int i, nu, nr, n = 0;
    if (0 <= iobsu && iobsu < obss->n) {
        settime((time = obss->data[iobsu].time));
    }
    if ((nu = nextobsf(obss, &iobsu, 1)) <= 0) return -1;
    if (popt->intpref) {
        for (; (nr = nextobsf(obss, &iobsr, 2)) > 0; iobsr += nr)
            if (timediff(obss->data[iobsr].time, obss->data[iobsu].time) > -DTTOL) break;
    } else {
        for (i = iobsr; (nr = nextobsf(obss, &i, 2)) > 0; iobsr = i, i += nr)
            if (timediff(obss->data[i].time, obss->data[iobsu].time) > DTTOL) break;
    }
    nr = nextobsf(obss, &iobsr, 2);
    for (i = 0; i < nu && n < MAXOBS * 2; i++) obs[n++] = obss->data[iobsu + i];
    for (i = 0; i < nr && n < MAXOBS * 2; i++) obs[n++] = obss->data[iobsr + i];
    iobsu += nu;
    return n;
}

